/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdminSeat.java
 *
 * Created on Apr 30, 2012, 7:01:58 PM
 */
package GUI.Admin;

import dao.ChoNgoiDAO;
import dao.PhongChieuDAO;
import java.awt.BorderLayout;
import java.util.List;
import javax.swing.ActionMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import main.MainFormApp;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.Task;
import pojo.Chongoi;
import pojo.Phongchieu;
import utils.BusyIndicator;
import utils.BusyIndicatorInputBlocker;
import utils.ClassUtils;

/**
 *
 * @author Hnmtuan
 */
public class AdminSeat extends javax.swing.JPanel {

    // <editor-fold defaultstate="collapsed" desc="Define all variables using this application">
    private SingleFrameApplication localApplication;
    private BusyIndicator localBusy;
    private ActionMap _rsActionMap;
    private boolean viewState, createState, deleteSate;
    private DefaultComboBoxModel _cbRoomModel;
    private List<Phongchieu> _rooms;
    public static int WIDTH_PANEL = 640;
    public static int HEIGHT_PANEL = 500;
    public static int DEFAULT_TOTAL_LABEL = 0;
    private static int DEFAULT_INDEX_COMBO = 0;
    // </editor-fold>
    //<editor-fold defaultstate="collapsed" desc="Define messages and error messages" >
    private final String ERR_PLACES_LIST_EMPTY = "Place list is empty";
    private final String ERR_ROOMS_LIST_EMPTY = "Room list is empty";
    private final String ERR_INVALID_PARAMS = "Invalid parameters !";
    private final String MSG_DELETE_SUCCESS = "Delete schedule successfully";
    private final String MSG_DELETE_BEGINNING = "Begin deleteing .... !";
    private final String MSG_DELETE_DATABASE = "Deleteing database  .... !";
    private final String MSG_DELETE_CONFIRM = "Do you want to delete all places of room %s ?";
    private final String MSG_DELETE_TITLE = "Delete Film Schedule";
    private final String ERR_DELETE_TASK = "Delete task not done !";
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Define Constructor" >

    public AdminSeat(SingleFrameApplication appContext, BusyIndicator busy) throws Exception {
        localApplication = appContext;
        localBusy = busy;
        initComponents();
        initActions();
        loadRooms();
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Define Init Actions" >

    private void initActions() throws Exception {
        _rsActionMap = Application.getInstance(main.MainFormApp.class).getContext().getActionMap(getClass(), this);
        jbtnView.setAction(_rsActionMap.get("viewSeat"));
        jbtnCreate.setAction(_rsActionMap.get("createSeat"));
        jbtnDelete.setAction(_rsActionMap.get("deleteSeat"));
        setViewState(true);
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Implement All Actions">

    @Action(enabledProperty = "viewState")
    public Task viewSeat() {
        Task task = new ViewTask();
        task.setInputBlocker(new BusyIndicatorInputBlocker(task, this.localBusy));
        return task;
    }

    @Action(enabledProperty = "createState")
    public Task createSeat() {
        Task task = new CreateTask();
        task.setInputBlocker(new BusyIndicatorInputBlocker(task, this.localBusy));
        return task;
    }

    @Action(enabledProperty = "deleteState")
    public Task deleteSeat() {
        Task task = new DeleteTask();
        task.setInputBlocker(new BusyIndicatorInputBlocker(task, this.localBusy));
        return task;
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Implement All Property or State">

    public boolean isViewState() {
        return viewState;
    }

    public boolean isCreateState() {
        return createState;
    }

    public boolean isDeleteState() {
        return deleteSate;
    }

    public void setViewState(boolean paramView) {
        if (this.viewState != paramView) {
            this.viewState = paramView;
            firePropertyChange("viewState", !this.viewState, this.viewState);
        }
    }

    public void setCreateState(boolean paramView) {
        if (this.createState != paramView) {
            this.createState = paramView;
            firePropertyChange("createState", !this.createState, this.createState);
        }
    }

    public void setDeleteSeat(boolean paramView) {
        if (this.deleteSate != paramView) {
            this.deleteSate = paramView;
            firePropertyChange("deleteState", !this.deleteSate, this.deleteSate);
        }
    }

    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Implement Actions to GUI" >
    protected final void defaultAllComboBox() {
        jcbRoom.setSelectedIndex(DEFAULT_INDEX_COMBO);
    }

    protected final void updateTotalLabel(int total) {
        this.jlbTotalSeats.setText(String.format("%d", total));
    }

    protected final Phongchieu getSelectedRoom() throws Exception {
        Phongchieu cachedRoom = null;
        if (_rooms == null || _rooms.size() < 1) {
            throw new Exception(ERR_ROOMS_LIST_EMPTY);
        }
        int selectedIndex = jcbRoom.getSelectedIndex();
        cachedRoom = _rooms.get(selectedIndex);
        return cachedRoom;
    }

    protected final void clearAllContent() {
        this.jpnSeats.removeAll();
    }

    protected final void defaultButtonState() {
        setViewState(true);
        setCreateState(false);
        setDeleteSeat(false);
        clearAllContent();
    }

    protected final void loadRooms() throws Exception {
        _cbRoomModel = (DefaultComboBoxModel) jcbRoom.getModel();
        _cbRoomModel.removeAllElements();
        try {
            _rooms = PhongChieuDAO.getPhongChieus();
            if (_rooms == null) {
                throw new Exception(ERR_ROOMS_LIST_EMPTY);
            }
            for (Phongchieu room : _rooms) {
                _cbRoomModel.addElement(room.getTenPhong());
            }
            jcbRoom.setModel(_cbRoomModel);
        } catch (Exception ex) {
            throw new Exception(ex.getMessage());
        } finally {
            PhongChieuDAO.closeCurrentSession();
        }
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Define View Task" >

    private class ViewTask extends Task<Void, Void> {

        public ViewTask() {
            super(localApplication);
        }

        @Override
        protected Void doInBackground() throws Exception {
            // get room which is selected from combobox
            Phongchieu cachedRoom = getSelectedRoom();
            if (cachedRoom == null) {
                throw new Exception(ERR_INVALID_PARAMS);
            }
            // get places from this room
            List<Chongoi> cachedPlaces = ChoNgoiDAO.getChoNgoiByPhongChieu(cachedRoom);
            int numPlaces = cachedPlaces.size();
            // if it don't have place, so out here
            if (cachedPlaces == null || numPlaces < 1) {
                setCreateState(true);
                setDeleteSeat(false);
                clearAllContent();
                updateTotalLabel(numPlaces);
                throw new Exception(ERR_PLACES_LIST_EMPTY);
            }
            setCreateState(false);
            setDeleteSeat(true);
            // otherwise generate gui
            clearAllContent();
            JPanel generatedPanel = ClassUtils.generatePlacesUI(cachedRoom, cachedPlaces);
            jpnSeats.setLayout(new BorderLayout());
            jpnSeats.add(generatedPanel, BorderLayout.CENTER);
            // update total place to label total
            updateTotalLabel(numPlaces);
            MainFormApp.getApplication().getMainFrame().pack();
            return null;
        }

        @Override
        protected void cancelled() {
        }

        @Override
        protected void failed(Throwable thrwbl) {
            setMessage(thrwbl.getMessage());
        }

        @Override
        protected void succeeded(Void t) {
//            defaultButtonState();
        }
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Define Create Task" >

    private class CreateTask extends Task<Void, Void> {

        public CreateTask() {
            super(localApplication);
        }

        @Override
        protected Void doInBackground() throws Exception {
            //Get room which is selected
            Phongchieu cachedRoom = getSelectedRoom();
            if (cachedRoom == null) {
                throw new Exception(ERR_INVALID_PARAMS);
            }
            // If this room have any place, so delete them.
            //Create place with following room
            List<Chongoi> places = ChoNgoiDAO.generateChoNgoisFromPhongChieu(cachedRoom);
            ChoNgoiDAO.insertManyChoNgoi(places);
            // Update jpanel list
            //Update total label
            updateTotalLabel(places.size());
            // Disable this create button            
            return null;
        }

        @Override
        protected void cancelled() {
        }

        @Override
        protected void failed(Throwable thrwbl) {
            setMessage(thrwbl.getMessage());
        }

        @Override
        protected void succeeded(Void t) {
            defaultButtonState();
        }
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Define Delete Task" >

    private class DeleteTask extends Task<Void, Void> {

        public DeleteTask() {
            super(localApplication);
        }

        @Override
        protected Void doInBackground() throws Exception {
            // Get room which is selected
            Phongchieu cachedRoom = getSelectedRoom();
            if (cachedRoom == null) {
                throw new Exception(ERR_INVALID_PARAMS);
            }
            // Show confirm dialog
            String msg = String.format(MSG_DELETE_CONFIRM, cachedRoom.getTenPhong());
            int returnOptionDialog = JOptionPane.showConfirmDialog(localApplication.getMainFrame(), msg, MSG_DELETE_TITLE, JOptionPane.OK_CANCEL_OPTION);
            // If user cancel so on
            if (returnOptionDialog == JOptionPane.CANCEL_OPTION) {
                // nothing change
                return null;
            }
            // Get places from above room
            List<Chongoi> cachedPlaces = ChoNgoiDAO.getChoNgoiByPhongChieu(cachedRoom);
            int numPlaces = cachedPlaces.size();
            if (cachedPlaces == null || numPlaces < 1) {
                setCreateState(true);
                setDeleteSeat(false);
                clearAllContent();
                updateTotalLabel(numPlaces);
                throw new Exception(ERR_PLACES_LIST_EMPTY);
            }
            // Delete multi places to database
            ChoNgoiDAO.deleteManyChoNgoi(cachedPlaces);
            defaultButtonState();
            // Clear content
            clearAllContent();
            // default combobox
            defaultAllComboBox();
            updateTotalLabel(DEFAULT_TOTAL_LABEL);
            return null;
        }

        @Override
        protected void cancelled() {
            setMessage(ERR_DELETE_TASK);
        }

        @Override
        protected void failed(Throwable thrwbl) {
            setMessage(thrwbl.getMessage());
        }

        @Override
        protected void succeeded(Void t) {
            setMessage(MSG_DELETE_SUCCESS);
        }
    }
    // </editor-fold>

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jcbRoom = new javax.swing.JComboBox();
        jbtnView = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jpnSeats = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jlbTotalSeats = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jbtnCreate = new javax.swing.JButton();
        jbtnDelete = new javax.swing.JButton();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("GUI/Admin/resources/AdminSeat"); // NOI18N
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("jpRoom.title"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setText(bundle.getString("jlbRoom.title")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jcbRoom.setName("jcbRoom"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(AdminSeat.class);
        jbtnView.setText(resourceMap.getString("jbtnViewSeats.text")); // NOI18N
        jbtnView.setName("jbtnView"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(95, 95, 95)
                .addComponent(jLabel1)
                .addGap(59, 59, 59)
                .addComponent(jcbRoom, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(49, 49, 49)
                .addComponent(jbtnView, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(95, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jcbRoom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnView))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("jpSeat.title"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jpnSeats.setName("jpnSeats"); // NOI18N

        javax.swing.GroupLayout jpnSeatsLayout = new javax.swing.GroupLayout(jpnSeats);
        jpnSeats.setLayout(jpnSeatsLayout);
        jpnSeatsLayout.setHorizontalGroup(
            jpnSeatsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 635, Short.MAX_VALUE)
        );
        jpnSeatsLayout.setVerticalGroup(
            jpnSeatsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 275, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(jpnSeats);

        jLabel2.setText(bundle.getString("jlbTotalSeats.title")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jlbTotalSeats.setText(bundle.getString("jlbNumTotal.title")); // NOI18N
        jlbTotalSeats.setName("jlbTotalSeats"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 637, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jlbTotalSeats)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jlbTotalSeats)))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("jpActions.title"))); // NOI18N
        jPanel3.setName("jPanel3"); // NOI18N

        jbtnCreate.setText(bundle.getString("jbtnAddNewSeat.title")); // NOI18N
        jbtnCreate.setName("jbtnCreate"); // NOI18N

        jbtnDelete.setText(bundle.getString("jbtnDeleteSeat.title")); // NOI18N
        jbtnDelete.setName("jbtnDelete"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(128, 128, 128)
                .addComponent(jbtnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(115, 115, 115)
                .addComponent(jbtnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(144, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtnCreate)
                    .addComponent(jbtnDelete))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtnCreate;
    private javax.swing.JButton jbtnDelete;
    private javax.swing.JButton jbtnView;
    private javax.swing.JComboBox jcbRoom;
    private javax.swing.JLabel jlbTotalSeats;
    private javax.swing.JPanel jpnSeats;
    // End of variables declaration//GEN-END:variables
}
